/**
 * @Copyright: 东方龙水业科技有限公司，石家庄
 * @Author: Airwolf, 2008-02-28
 * @Version: 080228.001
 * 
 */
package com.ibsol.database
{
	import com.ibsol.model.Company;
	
    import flash.data.SQLConnection;
    import flash.data.SQLStatement;
    import flash.events.SQLErrorEvent;
    import flash.events.SQLEvent;
    
    import mx.controls.Alert;
    import mx.collections.ArrayCollection;
    
	public class CompanyDAO
	{
		//private var conn:DBConnManager = new DBConnManager("data/tourix.db");	
		//private	var sqlStr:SQLStatement = new SQLStatement();
		private var _tourixDBConn:SQLConnection;
		/**
		 * 获取缺省连接
		 */				
		public function CompanyDAO()
		{
			_tourixDBConn = DBConnManager.getConnection("tourix");
		}
		
		/**
		 * 读取company记录
		 * @param:	resultHandler:Function	result function adapter, return price item array collection
		 * 			faultHandler:Function	fault funcition adapter
		 */		
		public function loadCompany(resultHandler:Function, faultHandler:Function = null):void
		{
			var sqlStr:SQLStatement = new SQLStatement();
			sqlStr.sqlConnection = _tourixDBConn;
			sqlStr.text = "select * from company";
			sqlStr.addEventListener(SQLEvent.RESULT,
				function (event:SQLEvent):void
				{
					resultHandler.call(this, typeArray(sqlStr.getResult().data));
				});
			sqlStr.addEventListener(SQLErrorEvent.ERROR, faultHandler == null ? sqlErrorHandler : faultHandler);
			sqlStr.execute();
		    			
		}
		/**
		 * Converts array object to company array collection
		 * @param: a:Array array of objects returned by SQL
		 * @return: ArrayCollection of company after conversion from Array
		 */				
		private function typeArray(a:Array):ArrayCollection
		{
			if (a==null) return null;
			var ac:ArrayCollection = new ArrayCollection();
			for (var i:int; i<a.length; i++)
			{
				ac.addItem(typeObject(a[i]));
			}
			return ac;
		}		
		/**
		 * Converts database object to company class
		 * @param:	o:Object		database return object
		 * @return:	company		company object after conversion
		 */			
		private function typeObject(o:Object):Company
		{
			var p:Company = new Company();
			p.id = o.id;
			p.name = o.name;
			p.addr = o.addr;
			p.phone = o.phone;
			p.fax = o.fax;
			p.email = o.email;
			p.remark = o.remark;
			return p;
		}		
		/**
		 * Default SQL error handler, if above functions' fault handlers are null, this error handler is applied
		 * @param: event:SQLError	SQL Error event will be handled if there is an error
		 * @return: void
		 */		
		private function sqlErrorHandler(event:SQLErrorEvent):void
		{
			mx.controls.Alert.show(event.text, "Error");
			trace(event.text);
		}			

	}
}